"use client";

import * as React from "react";
import { useForm } from "react-hook-form";

import { zodResolver } from "@hookform/resolvers/zod";
import { TagTypeEnum } from "@prisma/client";
import { LoaderCircle, Plus } from "lucide-react";

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

import { TAG_TYPES, TAG_TYPE_MAP } from "@/types/enum";
import {
  type CreateTagDTO,
  type UpdateTagDTO,
  verifyCreateTag,
  verifyUpdateTag,
  createTag,
  getTagById,
  updateTag,
} from "@/modules/tag";
import { cn } from "@/lib/utils";
import { useEffect, useMemo, useState } from "react";

interface ActionButtonProps {
  refreshAsync: () => Promise<unknown>;
  id?: string;
}
const ActionButton = ({ refreshAsync, id = "" }: ActionButtonProps) => {
  const isEdit = !!id;
  const [open, setOpen] = useState(false);
  const form = useForm<CreateTagDTO | UpdateTagDTO>({
    resolver: zodResolver(isEdit ? verifyUpdateTag : verifyCreateTag),
    defaultValues: {
      name: "",
      type: TagTypeEnum.ALL,
    },
  });

  const createTagController = createTag();

  const updateTagController = updateTag();

  const getTagByIdController = getTagById(id as string);

  const tag = useMemo(() => {
    return getTagByIdController.data?.tag;
  }, [getTagByIdController]);

  async function handleSubmit(values: CreateTagDTO | UpdateTagDTO) {
    if (isEdit) {
      await updateTagController.runAsync(values as UpdateTagDTO);
    } else {
      await createTagController.runAsync(values as CreateTagDTO);
    }
    setOpen(false);
    await refreshAsync();
  }

  useEffect(() => {
    if (open) {
      if (isEdit) {
        form.setValue("name", tag?.name ?? "");
        form.setValue("type", tag?.type ?? "ALL");
        form.setValue("id", tag?.id ?? "");
        form.clearErrors();
      } else {
        form.reset();
        form.clearErrors();
      }
    }
  }, [form, open, tag]);

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button
          onClick={() => {
            setOpen(true);
          }}
        >
          <Plus className="mr-2 size-4 " />
          {isEdit ? "编辑标签" : "创建标签"}
        </Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{isEdit ? "编辑标签" : "创建标签"}</DialogTitle>
        </DialogHeader>
        <Form {...form}>
          <form autoComplete="off">
            <div className="grid gap-4">
              <FormField
                control={form.control}
                name="name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>名称</FormLabel>
                    <FormControl>
                      <Input placeholder="请输入名称" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="type"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>类型</FormLabel>
                    <Select onValueChange={field.onChange} value={field.value}>
                      <FormControl>
                        <SelectTrigger
                          className={cn({
                            "text-muted-foreground": !field.value,
                          })}
                        >
                          <SelectValue placeholder="请选择标签" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {TAG_TYPES.map((el) => (
                          <SelectItem key={el} value={el}>
                            {TAG_TYPE_MAP[el]}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <div className="flex justify-end">
                <Button
                  type="button"
                  disabled={createTagController.loading}
                  onClick={() => form.handleSubmit(handleSubmit)()}
                >
                  {createTagController.loading && (
                    <LoaderCircle className="mr-2 size-4 animate-spin" />
                  )}
                  {isEdit ? "保存" : "创建"}
                </Button>
              </div>
            </div>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
};

export default ActionButton;
